<template>
  <div>
    <!-- 顶部栏 -->
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="用户名"
        :rules="[
          { required: true, message: '请输入用户名' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="text"
        name="code"
        label="验证码"
        required
        placeholder="密码"
        :rules="[
          { required: true, message: '请输入验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          color="#ABA3D8"
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="加载中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/views/user/user.js'
import { saveToken } from '@/utils/token.js'
import homeVue from '../home/home.vue'
export default {
  name: 'logo',
  data () {
    return {
      mobile: '18212345678',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    // value是一个对象
    // key是表单中输入元素的name属性
    // 表单校验通过之后会触发的回调函数
    onSubmit (values) {
      console.log('submit', values)
      this.isLoading = true
      //发送登录请求
      userLogin(values)
        .then(res => {
          console.log(res)
          this.$toast.success('登录成功')
          // 登录成功之后,保存token
          saveToken(res.data.data)

          this.$router.push({ name: 'home' })
        })
        .catch(err => {
          this.$toast.fail('账号或验证码错误')
        })
        .then(() => {
          // 最后一个then,只要本次请求完成就会执行,不管成功还是失败
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less">
.van-nav-bar {
  // 增加选择器权重
  .van-nav-bar__content {
    background-color: #aba3d8;
  }
  .van-nav-bar__title {
    color: #fff;
  }
  .van-nav-bar__left {
    .van-icon-arrow-left {
      color: #fff;
    }
    .van-nav-bar__text {
      color: #fff;
    }
  }
}
</style>
